<template>
    <van-nav-bar :title="alertext" safe-area-inset-top @click-left="onClickLeft" left-text="返回" fixed="'true" placeholder
        left-arrow>

    </van-nav-bar>
    <div>
        <van-popup v-model:show="showPicker" round>
            <van-picker :columns="columns" @cancel="showPicker = false" @confirm="onConfirm" />
        </van-popup>
    </div>
    <van-form @submit="onSubmit">
        <van-cell-group inset>
            <van-field v-model="prjname" name="项目名称" label="项目名称" placeholder="请输入项目名称" right-icon="search" clearable
                @change="onSearch" :rules="[{ required: true, message: '请选择项目名称' }]" />
            <van-field v-model="code" readonly type="number" name="code" label="项目编码" placeholder="请点击搜索选择项目"
                :rules="[{ required: true, message: '没有选择项目，请点击搜索选择项目' }]" />
            <van-field name="worktype" label="岗位信息">
                <template #input>
                    <van-radio-group v-model="worktype" direction="horizontal">
                        <van-radio name="wqzsp">维权指示牌</van-radio>
                    </van-radio-group>
                </template>
            </van-field>
            <van-field name="wqzsp" label="上传图片" :rules="[{ required: true, message: '请上传维权指示牌' }]">
                <template #input>
                    <van-uploader :max-size="2 * 1024 * 1024" @oversize="onOversize" v-model="fileList"
                        :after-read="afterRead" :before-read="beforeRead" :max-count="1" aria-required=""/>
                </template>
            </van-field>
        </van-cell-group>
        <div style="margin: 16px;">
            <van-button round block type="primary" native-type="submit">
                提交
            </van-button>
        </div>
    </van-form>
</template>


<script>
// 1. 引入你需要的组件
import { Search, Form, Field, CellGroup, Picker, Popup, showToast, RadioGroup, Radio, Button, showDialog, NavBar, Uploader } from 'vant';
// 2. 引入组件样式
import 'vant/lib/index.css';
import { ref } from 'vue';
import axios from "axios";



export default {
    setup() {
        const onClickLeft = () => history.back();
        const columns = [];
        const oldcolumns = [];
        const prjname = ref('');
        const code = ref('');
        const username = ref('');
        const worktype = ref('1');
        const wqzsp = ref('');
        const showPicker = ref(false);
        const onConfirm = ({ selectedOptions }) => {
            showPicker.value = false;
            prjname.value = selectedOptions[0].text;
            code.value = selectedOptions[0].value;
        };
        //上传图片
        const fileList = ref([

        ]);
        const onOversize = (file) => {
            console.log(file);
            showToast('文件大小不能超过 2Mb');
        };
        const afterRead = (file) => {
            // 此时可以自行将文件上传至服务器
            file.status = 'uploading';
            file.message = '上传中...';
            console.log(file.content)
            const formData = new FormData();
            formData.append('file', file.content);
            // 调用后端接口
            axios.post('http://bs.bzjsgl.cn/admin/getdata/getwqinfo', formData).then((response) => {
                console.log('4444444444444444', response.data);
                if(response.data['data']['code'] == 0){
                    file.status = 'success';
                file.message = '上传成功';
                console.log(response.data['data']['imageName'])
                sessionStorage.setItem('imagename', response.data['data']['imageName'])
                sessionStorage.setItem('wqzspid', response.data['data']['id'])
                }else{
                file.status = 'error';
                file.message = '上传失败';
                }
            }).catch((error) => {
                console.error(error);
            });
        };
        const beforeRead = (file) => {
            const allowedTypes = ["image/png", "image/jpeg", "image/jpg"];
            const type = file.type;
            if (!allowedTypes.includes(type)) {
                showToast('请上传 png、jpg、jpeg 格式图片');
                return false; // 返回 false 则不继续上传
            }
            return true; // 返回 true 则继续上传
        }
        //上传图片
        const onSubmit = (values) => {
            axios.post('http://bs.bzjsgl.cn/wxapi/Messagetemplate/addwqzsp', {
                openid: sessionStorage.getItem('openid'),
                imageName:sessionStorage.getItem('imagename'),
                wqzspid:sessionStorage.getItem('wqzspid'),
                code: values['code'],
                worktype: values['worktype']
            })
                .then(res => {
                    if (res.data['code'] === 20000) {
                        showDialog({
                            message: '添加成功！',
                            theme: 'round-button',
                        }).then(() => {
                            history.back()
                            location.reload()
                        });

                    }
                })
                .catch(function (error) { // 请求失败处理
                    console.log(error)
                })
        };
        return {
            columns,
            code,
            username,
            worktype,
            wqzsp,
            oldcolumns,
            onConfirm,
            prjname,
            showPicker,
            onSubmit,
            onClickLeft,
            fileList,
            afterRead,
            beforeRead,
            onOversize
        }
    },
    data() {
        return {
            keyword: '',
            selectedValue: '',
        };
    },
    mounted() {
        axios.post('http://bs.bzjsgl.cn/wxapi/Messagetemplate/subjectListInfobyopenid', {
            openid: sessionStorage.getItem('openid'),
        })
            .then(res => {
                var newList = res.data['data']
                if (res.data['code'] === 20000) {
                    for (let i = 0; i < newList.length; i++) {
                        let newItem = { text: newList[i]['value'], value: newList[i]['address'] };
                        this.oldcolumns.push(newItem);
                    }
                    console.log(this.oldcolumns)
                }
            })
            .catch(function (error) { // 请求失败处理
                console.log(error)
            })
    },
    methods: {
        onSearch() {
            console.log('搜索关键词：', this.prjname);
            this.showPicker = true;
            this.columns = this.oldcolumns
            console.log(this.columns)
            if (this.prjname === '') {
                this.$forceUpdate();
                // return this.columns;
            } else {
                this.columns = this.columns.filter(item => item.text.includes(this.prjname));
                this.$forceUpdate();
                // return this.columns.filter(item => item.text.includes(this.keyword));
            }
        }
    },
    components: {
        [Search.name]: Search,
        [Form.name]: Form,
        [Field.name]: Field,
        [CellGroup.name]: CellGroup,
        [Picker.name]: Picker,
        [Popup.name]: Popup,
        [showToast.name]: showToast,
        [RadioGroup.name]: RadioGroup,
        [Radio.name]: Radio,
        [Button.name]: Button,
        [showDialog.name]: showDialog,
        [NavBar.name]: NavBar,
        [Uploader.name]: Uploader
    }
}
</script>
